package org.wu.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wu.reggie.entity.Category;
import org.wu.reggie.entity.Page;
import org.wu.reggie.exception.LogicException;
import org.wu.reggie.mapper.CategoryMapper;
import org.wu.reggie.mapper.DishMapper;
import org.wu.reggie.mapper.SetMealMapper;
import org.wu.reggie.service.CategoryService;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {


    @Autowired(required = false)
    private CategoryMapper categoryMapper;


    @Autowired(required = false)
    private DishMapper dishMapper;

    @Autowired(required = false)
    private SetMealMapper setMealMapper;

    // 保存类别
    @Override
    public void save(Category category) {
        // 1 补全参数
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateTime(LocalDateTime.now());
        categoryMapper.save(category);

    }

    @Override
    public void findByName(String name) {
        Integer count = categoryMapper.findByName(name);
        if (count >=1){
            throw new LogicException("请勿重复添加分类");
        }
    }

    @Override
    public Page<Category> findByPage(Integer page, Integer pageSize) {
        //  1 设置当前页与页面大小
        PageHelper.startPage(page,pageSize);
        // 2 查询数据出来
        List<Category> categoryList =  categoryMapper.findAll();
        // 3 把集合封装到PageInfo对象中
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
        // 4 把PageInfo的数据封装到page对象中
        Page<Category> pageResult = new Page<>(pageInfo.getList(), pageInfo.getTotal(), pageSize, page);
        return pageResult;
    }


    /**
     * 作用 根据id删除类别
     * @param id
     */
    @Override
    public void deleteById(Long id) {

        // 1 查询当前类别是否关联有菜品，返回的是菜品的总数
        long count = dishMapper.findDishCountByCategoryId(id);
        if (count>0){
            throw new LogicException("该类别关联了菜品，无法删除");
            // 异常类的作用 通知你当前程序出现何种类型问题，
        }

        // 2 查询当前套餐是否关联有菜品
        count = setMealMapper.findSetMealByCategoryId(id);
        if (count > 0){
            throw new LogicException("该类别关联了套餐，无法删除");
            // 异常类的作用 通知你当前程序出现问题类型问题
        }

        categoryMapper.deleteById(id);

    }

    /**
     * 作用 修改类别
     * @param category
     */
    @Override
    public void updateById(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateById(category);
    }

    /**
     * 作用 根据Type查询类别集合
     * @param type
     * @return
     */
    @Override
    public List<Category> list(Integer type) {
        return categoryMapper.list(type);
    }
}
